package com.flow.framework.core.system.initialization;

import com.flow.framework.core.system.listener.lifecycle.ISystemLifecycleListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 初始化被代理服务和和系统启动时需要初始化的事项
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/23
 */
@Slf4j
public class SystemInitialization implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 当spring的上下文初始化完成后，需要对系统的绑定框架进行初始化
     *
     * @param e 上下文时间监听对象
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent e) {
        ApplicationContext context = e.getApplicationContext();
        ApplicationContext parent = context.getParent();

        // 非springboot启动时可能会存在通知多次的情况，如果父上下文为空，则说明还没有初始化完成
        if (null == parent) {
            return;
        }

        // spring cloud 场景下，如果父上下文的父上下文不为空，则说明spring还未初始化完成
        if (null != parent.getParent()) {
            return;
        }

        ApplicationContextHelper.setApplicationContext(context);
        Validator validator = context.getBean(Validator.class);
        ValidationHelper.setValidator(validator);

        ProxyManager.loadProxyBeans();

        Collection<ISystemLifecycleListener> initBeans = ApplicationContextHelper.getBeans(ISystemLifecycleListener.class);
        List<ISystemLifecycleListener> initializationListeners = new ArrayList<>(initBeans);
        initializationListeners.sort((e1, e2) -> e2.getOrder() - e1.getOrder());
        for (ISystemLifecycleListener initializationListener : initializationListeners) {
            initializationListener.onStartUp();
        }
    }
}
